package com.ruoyi.system.controller.standard;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.system.domain.standard_relevant.Standard;
import com.ruoyi.system.domain.standard_relevant.StandardExcel;
import com.ruoyi.system.domain.standard_relevant.StandardIEC;
import com.ruoyi.system.domain.standard_relevant.StandardISO;
import com.ruoyi.system.service.standard.IStandardExcelService;
import com.ruoyi.system.service.standard.IStandardIECService;
import com.ruoyi.system.service.standard.IStandardISOService;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.standard.IStandardService;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * 标准相关操作Controller
 *
 * @author ruoyi
 * @date 2024-07-06
 */
@RestController
@RequestMapping("/standards")
public class StandardController extends BaseController
{
    @Autowired
    private IStandardService standardService;

    @Autowired
    private IStandardISOService standardISOService;

    @Autowired
    private IStandardIECService standardIECService;

    @Autowired
    private IStandardExcelService standardExcelService;



    /**
     * new ---------------------------------------------------------
     */
    /**
     * 删除标准 by standardCode
     */
    @PreAuthorize("@ss.hasPermi('system:standard:remove')")
    @Log(title = "删除标准", businessType = BusinessType.DELETE)
    @PostMapping("/remove/byCode")
    public AjaxResult remove(@RequestBody String jsonCode)
    {
        try {
            JSONObject jsonObject = JSON.parseObject(jsonCode);
            String standardCode = jsonObject.getString("standardCode");
            String organization = jsonObject.getString("organization");

            // 删除 standard 表数据
            int res1 = standardService.deleteStandardByCode(standardCode);
            if(res1 <=0)return AjaxResult.error("删除标准基本信息失败");

            // 删除 standard_iso / standard_iec 里面的数据
            int res2 = 0;
            if ("ISO".equals(organization)) {
                res2 = standardISOService.deleteStandardISOByCode(standardCode); // 注意这里应该是 ISO
            } else if ("IEC".equals(organization)) {
                res2 = standardIECService.deleteStandardIECByCode(standardCode);
            }
            if(res2 <=0)return AjaxResult.error("删除标准具体信息失败");

            // 删除 standard_excel 表数据
            standardExcelService.deleteStandardExcelByStandardCode(standardCode);

            return AjaxResult.success("删除成功");
        } catch (Exception e) {
            return AjaxResult.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 标准分类统计
     */
//    @PreAuthorize("@ss.hasPermi('standard:base:count')")
    @Log(title = "标准相关操作", businessType = BusinessType.OTHER)
    @GetMapping("/classification")
    public AjaxResult countByClassificationCode(){
        return AjaxResult.success(standardService.countByClassificationCode());
    }

    /**
     * 查询指定标准号的 具体信息    ISO/IEC 的具体信息
     */
    @PreAuthorize("@ss.hasPermi('system:standard:view')")
    @Log(title = "查询标准具体信息", businessType = BusinessType.OTHER)
    @PostMapping("/detail/query/byCode")
    public AjaxResult getDetailByStandardCode(@RequestBody String jsonCode){
        JSONObject jsonObject = JSON.parseObject(jsonCode);
        String standardCode = jsonObject.getString("standardCode");
        String organization = jsonObject.getString("organization");

        if(organization.equals("ISO")){
            StandardISO standardISO = standardISOService.selectStandardISOByCode(standardCode);
            if (standardISO == null) {
                return AjaxResult.success("该标准尚未添加具体信息，请先添加具体信息");
            }
            return AjaxResult.success(standardISO);
        }else if (organization.equals("IEC")){
            StandardIEC standardIEC = standardIECService.selectStandardIECByCode(standardCode);
            if (standardIEC == null) {
                return AjaxResult.success("该标准尚未添加具体信息，请先添加具体信息");
            }
            return AjaxResult.success(standardIEC);
        }else{
            return AjaxResult.error("未找到相关标准");
        }
    }

    /**
     * 修改指定标准号的 具体信息
     */
    @PreAuthorize("@ss.hasPermi('system:standard:edit')")
    @Log(title = "修改标准具体信息", businessType = BusinessType.OTHER)
    @PutMapping("/detail")
    public AjaxResult updateDetailByStandardCode( @RequestBody JSONObject standard_JSON){
        String standardCode = standard_JSON.getString("standardCode");
        Standard target = standardService.selectStandardByCode(standardCode);
        if (target == null) {
            return AjaxResult.error("未找到标准基本信息");
        }

        String organization = target.getOrganization();

        if("ISO".equals(organization)){
            StandardISO standard = new StandardISO(
                    standard_JSON.getLong("id"),
                    standard_JSON.getString("standardCode"),
                    standard_JSON.getString("title"),
                    standard_JSON.getString("content"),
                    standard_JSON.getString("part"),
                    standard_JSON.getString("abstract_"),
                    standard_JSON.getString("status"),
                    standard_JSON.getString("publicationDate"),
                    standard_JSON.getString("stage"),
                    standard_JSON.getString("edition"),
                    standard_JSON.getString("numberOfPages"),
                    standard_JSON.getString("technicalCommittee"),
                    standard_JSON.getString("ics")
            );

            // 使用添加或更新方法
            int result = standardISOService.addOrUpdateStandardISO(standard);
            return toAjax(result);
        }else if ("IEC".equals(organization)){
            StandardIEC standard = new StandardIEC(
                    standard_JSON.getLong("id"),
                    standard_JSON.getString("standardCode"),
                    standard_JSON.getString("title"),
                    standard_JSON.getString("abstract_"),
                    standard_JSON.getString("publicationType"),
                    standard_JSON.getString("publicationDate"),
                    standard_JSON.getString("edition"),
                    standard_JSON.getString("availableLanguages"),
                    standard_JSON.getString("TC_SC"),
                    standard_JSON.getString("ics"),
                    standard_JSON.getString("pages"),
                    standard_JSON.getString("relatedPublications")
            );

            // 使用添加或更新方法
            int result = standardIECService.addOrUpdateStandardIEC(standard);
            return toAjax(result);

        }else{
            return AjaxResult.error("未找到相关标准");
        }
    }


    /**
     * 查询标准相关操作列表 ------ 条件查询
     */
    @PreAuthorize("@ss.hasPermi('system:standard:query')")
    @GetMapping("/list")
    public TableDataInfo list(Standard standard)
    {
        startPage();
        List<Standard> list = standardService.selectStandardList(standard);
        return getDataTable(list);
    }

    /**
     * 根据标准号查询excel(标准三级指标)
     */
    @PreAuthorize("@ss.hasPermi('system:standard:view_original')")
    @Log(title = "查询标准原始数据得分", businessType = BusinessType.OTHER)
    @PostMapping("/excel/query/byCode")
    public AjaxResult getStandardExcelByStandardCode(@RequestBody String jsonCode)
    {
        JSONObject jsonObject = JSON.parseObject(jsonCode);
        String standardCode = jsonObject.getString("standardCode");
        return AjaxResult.success(standardExcelService.selectStandardExcelByStandardCode(standardCode));
    }

    /**
     * 修改 标准三级指标
     */
    @PreAuthorize("@ss.hasPermi('system:standard:edit_original')")
    @Log(title = "修改标准原始数据得分", businessType = BusinessType.UPDATE)
    @PutMapping("/excel")
    public AjaxResult updateStandardExcel(@RequestBody JSONObject data) {
        StandardExcel standardExcel = new StandardExcel(
                data.getLong("id"),
                data.getString("standardCode"),
                Long.parseLong(data.getString("a11")),
                Long.parseLong(data.getString("a12")),
                Long.parseLong(data.getString("a13")),
                Long.parseLong(data.getString("b11")),
                Long.parseLong(data.getString("b12")),
                Long.parseLong(data.getString("b13")),
                Long.parseLong(data.getString("b14")),
                Long.parseLong(data.getString("b21")),
                Long.parseLong(data.getString("b22")),
                Long.parseLong(data.getString("b23")),
                Long.parseLong(data.getString("b24")),
                Long.parseLong(data.getString("b31")),
                Long.parseLong(data.getString("b32")),
                Long.parseLong(data.getString("b33")),
                Long.parseLong(data.getString("b41")),
                Long.parseLong(data.getString("b42")),
                Long.parseLong(data.getString("b43")),
                Long.parseLong(data.getString("b44"))
        );
        return toAjax(standardExcelService.updateStandardExcel(standardExcel));
    }

    /**
     * 查询 所有存在的标准号--列表
     */
//    @PreAuthorize("@ss.hasPermi('system:standard:query')")
    @Log(title = "查询所有存在的标准号", businessType = BusinessType.OTHER)
    @GetMapping("/allCode")
    public AjaxResult selectAllStandardCode()
    {
        return AjaxResult.success(standardService.selectAllStandardCode());
    }

    /**
     * 新增标准 ---- base
     */
    @PreAuthorize("@ss.hasPermi('system:standard:add')")
    @Log(title = "标准相关操作", businessType = BusinessType.INSERT)
    @PostMapping("/add/base")
    public AjaxResult add(@RequestBody JSONObject data)
    {
        Long id = Long.parseLong("1");
        String standardCode = data.getString("standardCode");
        String standardName = data.getString("standardName");
        String standardCname = data.getString("standardCname");
        String classificationCode = data.getString("classificationCode");
        String organization = data.getString("organization");
        String remark = data.getString("remark");
        String createUser = data.getString("createUser");
        Standard newStandard = new Standard(id, standardCode, standardName,standardCname ,classificationCode, organization, createUser, null,null, null, null);
        newStandard.setRemark(remark);
        newStandard.setUserId(getUserId());
        newStandard.setDeptId(getDeptId());

        return toAjax(standardService.insertStandard(newStandard));
    }
    /**
     *  新增标准 ---- ISO
     */
    @PreAuthorize("@ss.hasPermi('system:standard:add')")
    @Log(title = "标准相关操作", businessType = BusinessType.INSERT)
    @PostMapping("/add/ISO")
    public AjaxResult addISO(@RequestBody JSONObject data){
        Long id = Long.parseLong("1");
        String standardCode = data.getString("standardCode");
        String title = data.getString("title");
        String content = data.getString("content");
        String part = data.getString("part");
        String abstract_ = data.getString("abstract_");
        String status = data.getString("status");
        String publicationDate = data.getString("publicationDate");
        String stage = data.getString("stage");
        String edition = data.getString("edition");
        String numberOfPages = data.getString("numberOfPages");
        String technicalCommittee = data.getString("technicalCommittee");
        String ics = data.getString("ics");

        StandardISO newISO= new StandardISO(id, standardCode, title, content, part, abstract_, status, publicationDate, stage, edition, numberOfPages, technicalCommittee, ics);
        return toAjax(standardISOService.insertStandardISO(newISO));
    }

    /**
     * 新增标准 ---- IEC
     */
    @PreAuthorize("@ss.hasPermi('system:standard:add')")
    @Log(title = "标准相关操作", businessType = BusinessType.INSERT)
    @PostMapping("/add/IEC")
    public AjaxResult addIEC(@RequestBody JSONObject data){
        Long id = Long.parseLong("1");
        String standardCode = data.getString("standardCode");
        String title = data.getString("title");
        String abstract_ = data.getString("abstract_");
        String publicationType = data.getString("publicationType");
        String publicationDate = data.getString("publicationDate");
        String edition = data.getString("edition");
        String availableLanguages = data.getString("availableLanguages");
        String TC_SC = data.getString("TC_SC");
        String ics = data.getString("ICS");
        String pages = data.getString("pages");
        String relatedPublications = data.getString("relatedPublications");

        StandardIEC newIEC = new StandardIEC(id, standardCode, title, abstract_, publicationType, publicationDate, edition, availableLanguages, TC_SC, ics, pages, relatedPublications);
        return toAjax(standardIECService.insertStandardIEC(newIEC));
    }
}
